from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import random
from fractions import Fraction
import os
import webbrowser
import threading
import time

app = Flask(__name__, static_folder='static')
CORS(app)
# 生成题目函数
def generate_question(grade):
    """根据年级生成不同难度的题目"""
    if grade == 1:
        # 一年级：10以内加减法
        num1 = random.randint(0, 10)
        num2 = random.randint(0, 10)
        operation = random.choice(['+', '-'])
        if operation == '-':
            # 确保减法结果非负
            if num1 < num2:
                num1, num2 = num2, num1
        question = f"{num1} {operation} {num2}"
        answer = eval(question)
        return question, answer
    
    elif grade == 2:
        # 二年级：100以内加减法和表内乘法
        num1 = random.randint(0, 100)
        num2 = random.randint(0, 100)
        operation = random.choice(['+', '-', '*'])
        if operation == '-':
            if num1 < num2:
                num1, num2 = num2, num1
        elif operation == '*':
            # 表内乘法（1-9的乘法）
            num1 = random.randint(1, 9)
            num2 = random.randint(1, 9)
        question = f"{num1} {operation} {num2}"
        answer = eval(question)
        return question, answer
    
    elif grade == 3:
        # 三年级：1000以内加减法、表内乘除法
        num1 = random.randint(0, 1000)
        num2 = random.randint(0, 1000)
        operation = random.choice(['+', '-', '*', '/'])
        if operation == '-':
            if num1 < num2:
                num1, num2 = num2, num1
        elif operation == '*':
            num1 = random.randint(1, 30)
            num2 = random.randint(1, 30)
        elif operation == '/':
            # 除法，确保能整除
            num2 = random.randint(1, 20)
            num1 = num2 * random.randint(1, 20)
        question = f"{num1} {operation} {num2}"
        answer = eval(question)
        return question, answer
    
    elif grade == 4:
        # 四年级：整数四则混合运算
        num1 = random.randint(1, 100)
        num2 = random.randint(1, 100)
        num3 = random.randint(1, 100)
        operation1 = random.choice(['+', '-', '*'])
        operation2 = random.choice(['+', '-', '*'])
        question = f"{num1} {operation1} {num2} {operation2} {num3}"
        answer = eval(question)
        return question, answer
    
    elif grade == 5:
        # 五年级：加入分数运算（简单）
        if random.random() < 0.5:
            # 整数四则混合运算
            num1 = random.randint(1, 100)
            num2 = random.randint(1, 100)
            num3 = random.randint(1, 100)
            operation1 = random.choice(['+', '-', '*'])
            operation2 = random.choice(['+', '-'])
            question = f"{num1} {operation1} {num2} {operation2} {num3}"
            answer = eval(question)
        else:
            # 分数运算（同分母加法或减法）
            denominator = random.randint(2, 10)
            numerator1 = random.randint(1, 10)
            numerator2 = random.randint(1, 10)
            operation = random.choice(['+', '-'])
            
            if operation == '-':
                if numerator1 < numerator2:
                    numerator1, numerator2 = numerator2, numerator1
            
            f1 = Fraction(numerator1, denominator)
            f2 = Fraction(numerator2, denominator)
            
            if operation == '+':
                result = f1 + f2
            else:
                result = f1 - f2
            
            question = f"{numerator1}/{denominator} {operation} {numerator2}/{denominator}"
            answer = result
        return question, answer
    
    elif grade == 6:
        # 六年级：分数乘除法
        operation = random.choice(['+', '-', '*', '/'])
        
        if operation in ['+', '-']:
            # 分数加减法（可能不同分母）
            denominator1 = random.randint(2, 10)
            denominator2 = random.randint(2, 10)
            numerator1 = random.randint(1, 10)
            numerator2 = random.randint(1, 10)
            
            f1 = Fraction(numerator1, denominator1)
            f2 = Fraction(numerator2, denominator2)
            
            if operation == '+':
                result = f1 + f2
            else:
                # 确保减法结果非负
                if f1 < f2:
                    f1, f2 = f2, f1
                    numerator1, numerator2 = numerator2, numerator1
                    denominator1, denominator2 = denominator2, denominator1
                result = f1 - f2
            
            question = f"{numerator1}/{denominator1} {operation} {numerator2}/{denominator2}"
        else:
            # 分数乘除法
            denominator1 = random.randint(2, 10)
            denominator2 = random.randint(2, 10)
            numerator1 = random.randint(1, 10)
            numerator2 = random.randint(1, 10)
            
            f1 = Fraction(numerator1, denominator1)
            f2 = Fraction(numerator2, denominator2)
            
            if operation == '*':
                result = f1 * f2
            else:
                # 除法，交换分子分母
                f2 = Fraction(denominator2, numerator2)
                result = f1 * f2
            
            question = f"{numerator1}/{denominator1} {operation} {numerator2}/{denominator2}"
        
        answer = result
        return question, answer

# API端点：生成题目
@app.route('/api/generate', methods=['POST'])
def generate():
    data = request.json
    grade = data.get('grade', 1)
    
    if grade < 1 or grade > 6:
        return jsonify({'error': '年级必须在1-6之间'}), 400
    
    question, answer = generate_question(grade)
    
    # 格式化答案，对于分数进行特殊处理
    if isinstance(answer, Fraction):
        answer_str = f"{answer.numerator}/{answer.denominator}" if answer.denominator != 1 else str(answer.numerator)
    else:
        answer_str = str(answer)
    
    return jsonify({
        'question': question,
        'answer': answer_str
    })

# API端点：验证答案
@app.route('/api/check', methods=['POST'])
def check_answer():
    data = request.json
    user_answer = data.get('answer', '')
    correct_answer = data.get('correct_answer', '')
    
    # 去除空格进行比较
    user_answer = user_answer.strip()
    correct_answer = correct_answer.strip()
    
    # 对于分数，转换为Fraction对象进行比较
    try:
        # 尝试将答案转换为Fraction进行精确比较
        user_fraction = Fraction(user_answer)
        correct_fraction = Fraction(correct_answer)
        is_correct = user_fraction == correct_fraction
    except:
        # 如果转换失败，使用字符串比较
        is_correct = user_answer == correct_answer
    
    return jsonify({
        'correct': is_correct
    })

# 提供静态文件
@app.route('/')
def index():
    return send_from_directory('static', 'index.html')

@app.route('/static/<path:path>')
def send_static(path):
    return send_from_directory('static', path)

# 启动浏览器的函数
def open_browser():
    time.sleep(2)  # 等待服务器启动
    webbrowser.open_new('http://127.0.0.1:5000/')

if __name__ == '__main__':
    # 在新线程中启动浏览器
    threading.Thread(target=open_browser).start()
    # 启动服务器
    app.run(debug=True, port=5000)